<template>
  <div class="show-view">
    <div class="header">
      <h1>店铺数据概览</h1>
      
      <div class="header-controls">
        <div class="shop-selector" v-if="userShops.length > 0">
          <label>当前店铺:</label>
          <select v-model="selectedShopId" @change="handleShopChange" v-if="userShops.length > 1">
            <option v-for="shop in userShops" :key="shop.id" :value="shop.id">
              {{ shop.name }}
            </option>
          </select>
          <span v-else class="single-shop-name">{{ userShops[0]?.name || '未命名店铺' }}</span>
        </div>
        <div class="date-picker">
          <select v-model="selectedDateRange" @change="handleDateRangeChange">
            <option value="week">本周</option>
            <option value="month">本月</option>
            <option value="quarter">本季度</option>
          </select>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>正在加载统计数据...</p>
    </div>

    <div v-else class="stats-grid">
      <div class="stat-card">
        <div class="icon revenue">
          <i class="fas fa-money-bill-wave"></i>
        </div>
        <div class="info">
          <h3>¥{{ stats.totalRevenue }}</h3>
          <p>总营业额</p>
        </div>
        <div class="trend up">+12.5%</div>
      </div>

      <div class="stat-card">
        <div class="icon orders">
          <i class="fas fa-shopping-bag"></i>
        </div>
        <div class="info">
          <h3>{{ stats.totalOrders }}</h3>
          <p>总订单数</p>
        </div>
        <div class="trend up">+8.2%</div>
      </div>

      <div class="stat-card">
        <div class="icon customers">
          <i class="fas fa-users"></i>
        </div>
        <div class="info">
          <h3>{{ stats.newCustomers }}</h3>
          <p>新顾客</p>
        </div>
        <div class="trend down">-3.1%</div>
      </div>

      <div class="stat-card">
        <div class="icon rating">
          <i class="fas fa-star"></i>
        </div>
        <div class="info">
          <h3>{{ stats.avgRating }}</h3>
          <p>平均评分</p>
        </div>
        <div class="trend up">+0.2</div>
      </div>
    </div>

    <div class="charts-container">
      <div class="chart-card">
        <h2>销售额趋势</h2>
        <div class="chart-placeholder revenue-chart">
          <div class="chart-bar" v-for="(item, index) in revenueData" :key="index" 
               :style="{ height: item.height + '%' }">
            <span class="bar-value">¥{{ item.value }}</span>
          </div>
        </div>
      </div>

      <div class="chart-card">
        <h2>订单量趋势</h2>
        <div class="chart-placeholder orders-chart">
          <div class="chart-bar" v-for="(item, index) in ordersData" :key="index" 
               :style="{ height: item.height + '%' }">
            <span class="bar-value">{{ item.value }}</span>
          </div>
        </div>
      </div>
    </div>

    <div class="popular-items">
      <h2>最受欢迎菜品</h2>
      <div class="items-grid">
        <div v-for="(item, index) in popularItems" :key="index" class="item-card">
          <div class="item-rank">{{ index + 1 }}</div>
          <div class="item-image" :style="{ backgroundImage: `url(${item.image})` }"></div>
          <div class="item-info">
            <h3>{{ item.name }}</h3>
            <p>销量: {{ item.sales }}份</p>
            <div class="rating">评分: <span>{{ item.rating }}</span></div>
          </div>
          <div class="item-revenue">¥{{ item.revenue }}</div>
        </div>
      </div>
    </div>

    <div class="recent-orders">
      <h2>最近订单</h2>
      <table>
        <thead>
          <tr>
            <th>订单号</th>
            <th>时间</th>
            <th>金额</th>
            <th>状态</th>
            <th>顾客</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(order, index) in recentOrders" :key="index">
            <td>#{{ order.id }}</td>
            <td>{{ order.time }}</td>
            <td>¥{{ order.amount }}</td>
            <td><span :class="order.status">{{ order.statusText }}</span></td>
            <td>{{ order.customer }}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useUserIdStore } from '@/stores/UserId';
import { selectEq as getShops } from '@/http/Shop';
import { getOrderStats, selectByShopId, type OrderStats } from '@/http/Order';
import { message } from '@/utils/message';

const userIdStore = useUserIdStore();
const selectedDateRange = ref('month');
const loading = ref(true);

// 店铺切换相关状态
const userShops = ref<Array<{id: number, name: string}>>([]);
const selectedShopId = ref<number | null>(null);

// 使用后端数据类型
const stats = ref<OrderStats>({
  totalRevenue: 0,
  totalOrders: 0,
  newCustomers: 0,
  avgRating: 0,
  monthlyRevenue: [],
  monthlyOrders: []
});

const popularItems = ref([
  { name: '麻辣小龙虾', sales: 156, rating: 4.9, revenue: 15288, image: '/food001.jpg' },
  { name: '蒜蓉烤生蚝', sales: 132, rating: 4.8, revenue: 11880, image: '/food002.jpg' },
  { name: '香辣烤鱼', sales: 98, rating: 4.7, revenue: 11760, image: '/food003.jpg' },
  { name: '招牌牛肉面', sales: 87, rating: 4.6, revenue: 5220, image: '/food004.jpg' },
  { name: '鲜榨西瓜汁', sales: 120, rating: 4.8, revenue: 3600, image: '/food005.jpg' },
  { name: '秘制羊肉串', sales: 105, rating: 4.7, revenue: 5250, image: '/food006.jpg' }
]);

const recentOrders = ref([
  { id: '20230615001', time: '14:25', amount: 128, status: 'completed', statusText: '已完成', customer: '张先生' },
  { id: '20230615002', time: '14:18', amount: 86, status: 'preparing', statusText: '准备中', customer: '李女士' },
  { id: '20230615003', time: '14:10', amount: 152, status: 'delivering', statusText: '配送中', customer: '王先生' },
  { id: '20230615004', time: '13:58', amount: 64, status: 'pending', statusText: '待接单', customer: '赵小姐' },
  { id: '20230615005', time: '13:45', amount: 98, status: 'completed', statusText: '已完成', customer: '陈先生' }
]);

// 加载用户的所有店铺
const loadUserShops = async () => {
  try {
    if (!userIdStore.currentUserId) {
      return;
    }

    const shopResponse = await getShops({ rela_user_id: userIdStore.currentUserId });
    
    if (shopResponse.data && shopResponse.data.length > 0) {
      userShops.value = shopResponse.data.map(shop => ({
        id: shop.id!,
        name: shop.name || '未命名店铺'
      }));
      
      // 默认选择第一个店铺
      if (!selectedShopId.value && userShops.value.length > 0) {
        selectedShopId.value = userShops.value[0].id;
      }
      
      console.log('✅ 用户店铺加载成功:', userShops.value.length, '个店铺');
    } else {
      console.log('⚠️ 用户没有店铺');
      userShops.value = [];
    }
  } catch (error: any) {
    console.error('❌ 加载用户店铺失败:', error);
    userShops.value = [];
  }
};

// 处理店铺切换
const handleShopChange = () => {
  console.log('🔄 切换店铺:', selectedShopId.value);
  loadStats();
};

// 加载统计数据
const loadStats = async () => {
  loading.value = true;
  try {
    console.log('🚀 开始加载统计数据...');
    
    // 首先尝试从本地存储恢复用户状态
    if (!userIdStore.currentUserId) {
      console.log('⚠️ 用户ID为空，尝试从本地存储恢复...');
      userIdStore.restoreFromStorage();
      
      if (!userIdStore.currentUserId) {
        console.log('❌ 恢复失败，用户未登录');
        message.warning('请先登录');
        return;
      } else {
        console.log('✅ 用户状态已从本地存储恢复:', userIdStore.currentUserId);
        message.success('欢迎回来！');
      }
    }

    // 如果没有加载过店铺列表，先加载
    if (userShops.value.length === 0) {
      await loadUserShops();
    }

    // 确保有选中的店铺
    if (!selectedShopId.value) {
      if (userShops.value.length === 0) {
        console.log('⚠️ 用户没有店铺');
        message.info('您还没有店铺，无法查看统计数据');
        loadMockData();
        return;
      } else {
        selectedShopId.value = userShops.value[0].id;
      }
    }

    const shopId = selectedShopId.value;
    console.log('🏪 使用店铺ID:', shopId);

    try {
      // 尝试获取订单统计数据
      const statsResponse = await getOrderStats(shopId!, selectedDateRange.value);
      
      if (statsResponse.data) {
        stats.value = statsResponse.data;
        console.log('✅ 统计数据加载成功:', statsResponse.data);
      } else {
        console.log('⚠️ 没有统计数据，使用模拟数据');
        loadMockData();
      }
    } catch (statsError: any) {
      console.log('⚠️ 统计接口暂未实现，使用模拟数据:', statsError.message);
      loadMockData();
    }

    try {
      // 尝试获取最近订单数据
      const ordersResponse = await selectByShopId(shopId!, 1, 10);
      
      if (ordersResponse.data && ordersResponse.data.list) {
        // 转换订单数据格式
        const convertedOrders = ordersResponse.data.list.map(order => ({
          id: order.id?.toString() || '',
          time: formatOrderTime(order.createTime),
          amount: order.actualPayment || 0,
          status: order.status || 'unknown',
          statusText: getStatusText(order.status),
          customer: '用户' + (order.relaUserId || '未知')
        }));
        
        recentOrders.value = convertedOrders;
        console.log('✅ 最近订单数据加载成功:', convertedOrders.length, '个订单');
      } else {
        console.log('⚠️ 没有订单数据，使用模拟数据');
        // recentOrders.value 保持默认的模拟数据
      }
    } catch (ordersError: any) {
      console.log('⚠️ 订单接口暂未实现，使用模拟数据:', ordersError.message);
      // recentOrders.value 保持默认的模拟数据
    }

  } catch (error: any) {
    console.error('❌ 加载统计数据失败:', error);
    
    // 详细错误处理
    let errorMessage = '加载统计数据失败';
    if (error.response) {
      const status = error.response.status;
      const data = error.response.data;
      
      if (status === 400) {
        errorMessage = '请求参数错误: ' + (data?.message || '数据格式不正确');
      } else if (status === 404) {
        errorMessage = '接口不存在，使用模拟数据展示';
        loadMockData();
        return; // 不显示错误消息，直接使用模拟数据
      } else if (status === 500) {
        errorMessage = '服务器内部错误';
      } else {
        errorMessage = `服务器错误 (${status}): ${data?.message || '未知错误'}`;
      }
    } else if (error.request) {
      errorMessage = '网络连接失败，请检查网络设置';
    } else {
      errorMessage = error.message || '未知错误';
    }
    
    message.error(errorMessage);
    
    // 错误时使用模拟数据作为备用
    loadMockData();
  } finally {
    loading.value = false;
  }
};

// 加载模拟数据
const loadMockData = () => {
  console.log('📊 使用模拟数据展示统计信息');
  stats.value = {
    totalRevenue: 28650,
    totalOrders: 156,
    newCustomers: 23,
    avgRating: 4.7,
    monthlyRevenue: [2450, 2870, 1980, 3120, 2760, 2250, 2950],
    monthlyOrders: [42, 58, 35, 62, 48, 39, 56]
  };
  
  // recentOrders.value 保持默认值
  message.info('当前显示模拟数据，实际数据需要后端接口支持');
};

// 格式化订单时间
const formatOrderTime = (timeString: string | null) => {
  if (!timeString) return '';
  
  try {
    const date = new Date(timeString);
    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    });
  } catch (error) {
    return timeString;
  }
};

// 获取状态文本
const getStatusText = (status: string | null) => {
  const statusMap: Record<string, string> = {
    'pending': '待接单',
    'confirmed': '已接单',
    'preparing': '准备中',
    'delivering': '配送中',
    'completed': '已完成',
    'cancelled': '已取消'
  };
  return statusMap[status || ''] || '未知状态';
};

// 页面加载时获取数据
onMounted(() => {
  loadStats();
});

// 监听日期范围变化
const handleDateRangeChange = () => {
  loadStats();
};

// 模拟图表数据
const revenueData = computed(() => {
  if (stats.value.monthlyRevenue && stats.value.monthlyRevenue.length > 0) {
    const maxValue = Math.max(...stats.value.monthlyRevenue);
    return stats.value.monthlyRevenue.map(value => ({
      value: value,
      height: maxValue > 0 ? (value / maxValue) * 100 : 0
    }));
  }
  
  // 备用静态数据
  const maxValue = 3000;
  return [
    { value: 2450, height: (2450 / maxValue) * 100 },
    { value: 2870, height: (2870 / maxValue) * 100 },
    { value: 1980, height: (1980 / maxValue) * 100 },
    { value: 3120, height: (3120 / maxValue) * 100 },
    { value: 2760, height: (2760 / maxValue) * 100 },
    { value: 2250, height: (2250 / maxValue) * 100 },
    { value: 2950, height: (2950 / maxValue) * 100 }
  ];
});

const ordersData = computed(() => {
  if (stats.value.monthlyOrders && stats.value.monthlyOrders.length > 0) {
    const maxValue = Math.max(...stats.value.monthlyOrders);
    return stats.value.monthlyOrders.map(value => ({
      value: value,
      height: maxValue > 0 ? (value / maxValue) * 100 : 0
    }));
  }
  
  // 备用静态数据
  const maxValue = 70;
  return [
    { value: 42, height: (42 / maxValue) * 100 },
    { value: 58, height: (58 / maxValue) * 100 },
    { value: 35, height: (35 / maxValue) * 100 },
    { value: 62, height: (62 / maxValue) * 100 },
    { value: 48, height: (48 / maxValue) * 100 },
    { value: 39, height: (39 / maxValue) * 100 },
    { value: 56, height: (56 / maxValue) * 100 }
  ];
});
</script>

<style scoped>
.show-view {
  width: 100%;
  height: 100vh;
  padding: 30px;
  background: #f8fafc;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  overflow-y: auto;
  box-sizing: border-box;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.header h1 {
  color: #2d3748;
  font-size: 28px;
  font-weight: 700;
}

.header-controls {
  display: flex;
  align-items: center;
}

.shop-selector {
  margin-right: 20px;
}

.shop-selector label {
  margin-right: 10px;
}

.shop-selector select {
  padding: 10px 15px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  background: white;
  color: #4a5568;
  font-size: 14px;
  cursor: pointer;
  outline: none;
  transition: all 0.3s;
}

.shop-selector select:focus {
  border-color: #4299e1;
  box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.2);
}

.single-shop-name {
  padding: 10px 15px;
  background: #f7fafc;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  color: #2d3748;
  font-size: 14px;
  font-weight: 600;
}

.date-picker select {
  padding: 10px 15px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  background: white;
  color: #4a5568;
  font-size: 14px;
  cursor: pointer;
  outline: none;
  transition: all 0.3s;
}

.date-picker select:focus {
  border-color: #4299e1;
  box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.2);
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  transition: transform 0.3s, box-shadow 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.08);
}

.icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
  margin-right: 15px;
}

.icon.revenue {
  background: linear-gradient(135deg, #4caf50, #8bc34a);
}

.icon.orders {
  background: linear-gradient(135deg, #2196f3, #03a9f4);
}

.icon.customers {
  background: linear-gradient(135deg, #ff9800, #ffc107);
}

.icon.rating {
  background: linear-gradient(135deg, #f44336, #ff9800);
}

.info h3 {
  margin: 0 0 5px;
  font-size: 22px;
  color: #2d3748;
}

.info p {
  margin: 0;
  color: #718096;
  font-size: 14px;
}

.trend {
  margin-left: auto;
  font-weight: 700;
  font-size: 14px;
}

.trend.up {
  color: #4caf50;
}

.trend.down {
  color: #f44336;
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.chart-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.chart-card h2 {
  margin: 0 0 20px;
  color: #2d3748;
  font-size: 18px;
}

.chart-placeholder {
  height: 200px;
  display: flex;
  align-items: flex-end;
  gap: 15px;
  padding: 0 20px;
}

.chart-bar {
  flex: 1;
  background: linear-gradient(to top, #4299e1, #90cdf4);
  border-radius: 6px 6px 0 0;
  position: relative;
  min-height: 2px;
  transition: height 0.5s ease;
}

.bar-value {
  position: absolute;
  top: -25px;
  left: 0;
  right: 0;
  text-align: center;
  font-size: 12px;
  font-weight: 600;
  color: #2d3748;
}

.revenue-chart .chart-bar {
  background: linear-gradient(to top, #4caf50, #8bc34a);
}

.popular-items {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 30px;
}

.popular-items h2 {
  margin: 0 0 20px;
  color: #2d3748;
  font-size: 18px;
}

.items-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 15px;
}

.item-card {
  display: flex;
  align-items: center;
  padding: 15px;
  border-radius: 10px;
  background: #f8fafc;
  transition: all 0.3s;
}

.item-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.item-rank {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: #4299e1;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-right: 15px;
}

.item-card:nth-child(1) .item-rank {
  background: linear-gradient(135deg, #ff9800, #ffc107);
}

.item-card:nth-child(2) .item-rank {
  background: linear-gradient(135deg, #9e9e9e, #e0e0e0);
}

.item-card:nth-child(3) .item-rank {
  background: linear-gradient(135deg, #795548, #a1887f);
}

.item-image {
  width: 60px;
  height: 60px;
  border-radius: 10px;
  background-size: cover;
  background-position: center;
  margin-right: 15px;
}

.item-info {
  flex: 1;
}

.item-info h3 {
  margin: 0 0 5px;
  font-size: 16px;
  color: #2d3748;
}

.item-info p {
  margin: 0 0 3px;
  font-size: 13px;
  color: #718096;
}

.rating {
  font-size: 13px;
  color: #718096;
}

.rating span {
  color: #ff9800;
  font-weight: bold;
}

.item-revenue {
  font-weight: bold;
  font-size: 18px;
  color: #4caf50;
}

.recent-orders {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.recent-orders h2 {
  margin: 0 0 20px;
  color: #2d3748;
  font-size: 18px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #e2e8f0;
}

th {
  color: #718096;
  font-weight: 600;
  font-size: 14px;
}

td {
  color: #2d3748;
  font-size: 14px;
}

tr:hover td {
  background: #f8fafc;
}

.completed {
  background: #e8f5e9;
  color: #4caf50;
  padding: 5px 10px;
  border-radius: 20px;
  font-size: 12px;
}

.preparing {
  background: #fffde7;
  color: #ff9800;
  padding: 5px 10px;
  border-radius: 20px;
  font-size: 12px;
}

.delivering {
  background: #e3f2fd;
  color: #2196f3;
  padding: 5px 10px;
  border-radius: 20px;
  font-size: 12px;
}

.pending {
  background: #ffebee;
  color: #f44336;
  padding: 5px 10px;
  border-radius: 20px;
  font-size: 12px;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #4299e1;
  border-top: 4px solid transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-container p {
  color: #718096;
  font-size: 16px;
  margin: 0;
}
</style>